import { createRouter, createWebHashHistory } from 'vue-router'
import useSys from '@/store/useSys.js'
import Layout from '@/views/Layout.vue'
import Login from '@/views/Login.vue'
import Register from '@/views/Register.vue'
import Bridge from '@/views/Bridge.vue';
let routes = [
    {
        path: "/",
        name: "index",
        component: Layout,
        children: [
            {
                path: "/",
                name: "home",
                component: () => import("@/views/Home.vue")
            }
        ]
    },
    {
        path: "/login",
        name: "login",
        component: Login
    },
    {
        path: "/register",
        name: "register",
        component: Register
    }
]
let router = createRouter({
    history: createWebHashHistory(),
    routes
});
//全局守卫：前置守卫，进入路由之前先进入他
//to:现在要进入哪个路由
//from:从哪个路由进去
//next:如果不执行，那么他去不了to
//sessionStorage:前台的会话对象，浏览器关闭，立马清空
let isFirst = true
router.beforeEach((to, from, next) => {
    console.log(to.path);

    if (to.path == '/login' || to.path == '/register') {
        next();
        return;
    }
    let sys = useSys();
    if (!sys.treeMenus) {//如果你是第一次加载，那么就需要重新的去获取菜单和路由数据
        if (sys.runFangs != 'dev') {
            let token = sys.sessionToken
            if (!token) {
                console.log("进入登录")
                next("/login");
                return;
            }
        }

        console.log("加载菜单")
        //加载菜单
        sys.loadMenus().then(resp => {
            isFirst = false;
            //重复跳转一次
            let routerName = sessionStorage.getItem("routerName")
            if (routerName) {
                next({ path: routerName });
            } else {
                next({ path: "/" })
            }
        })
    } else {
        sessionStorage.setItem('routerName', to.path)
        next();
    }
});
//全局守卫：后置守卫，离开路由后会进入他
// router.afterEach();

export default router;